/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：统一替换画布下的所有Text字体
* CreateTime：2021-05-11 10:03:41
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace TinyToolKitEditor
{
    public class SwitchFontWindow : EditorWindow
    {
        private static SwitchFontWindow _instance;

        private Transform _root;
        private Font _font;
        private int count;

        public static void ShowWindow()
        {
            _instance = GetWindow<SwitchFontWindow>();
            _instance.titleContent = new GUIContent("Switch Font");
            _instance.maxSize = new Vector2(250,120);
            _instance.minSize = new Vector2(250,120);
            _instance.Show();
        }

        private void OnGUI()
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("替换根目录下所有Text组件的字体");
            EditorGUILayout.Space();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Root:",GUILayout.Width(50));
            _root = EditorGUILayout.ObjectField(_root, typeof(Transform), true) as Transform; 
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Font:",GUILayout.Width(50));
            _font = EditorGUILayout.ObjectField(_font, typeof(Font), true) as Font; 
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space();
            if (GUILayout.Button("替换"))
            {
                if (_root == null) return;

                count = 0;
                List<Text> texts = new List<Text>();
                GetAllText(_root, ref texts);

                foreach (var item in texts)
                {
                    count++;
                    Undo.RecordObject(item,item.gameObject.name);
                    item.font = _font;
                    EditorUtility.SetDirty(item.gameObject);
                }
            }
            EditorGUILayout.LabelField("修改字体个数：" + count);
        }

        private void GetAllText(Transform root,ref List<Text> texts)
        {
            for (int i = 0; i < root.childCount; i++)
            {
                Transform childRoot = root.GetChild(i);
                Text text = childRoot.GetComponent<Text>();
                if(text != null)
                    texts.Add(text);
                if (childRoot.childCount > 0)
                    GetAllText(childRoot, ref texts);
            }
        }
    }
}

